package org.lfh.wintersun.web.user.service.impl;

import java.io.*;
import java.net.URL;
import java.net.URLClassLoader;

public class CustomClassLoader extends URLClassLoader {

    public CustomClassLoader(URL[] urls) {
        super(urls);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        // 在这里，我们不调用父类加载器的loadClass方法，从而打破了双亲委派模型
        byte[] classData = loadClassData(name);
        if (classData == null) {
            throw new ClassNotFoundException();
        } else {
            return defineClass(name, classData, 0, classData.length);
        }
    }

    private byte[] loadClassData(String name) {
        String path = name.replace('.', '/') + ".class";
        try (InputStream inputStream = getClass().getResourceAsStream("/" + path);
             ByteArrayOutputStream byteStream = new ByteArrayOutputStream()) {

            if (inputStream == null) {
                return null;
            }

            int nextValue = 0;
            while ((nextValue = inputStream.read()) != -1) {
                byteStream.write(nextValue);
            }

            return byteStream.toByteArray();

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        try {
            // 假设我们有一个自定义的类com.example.MyClass，它位于项目的某个目录下
            File classDir = new File("path/to/classes");
            URL classUrl = classDir.toURI().toURL();
            URL[] urls = {classUrl};

            CustomClassLoader customClassLoader = new CustomClassLoader(urls);
            Class<?> myClass = customClassLoader.loadClass("com.example.MyClass");

            // 现在我们可以使用反射来实例化这个类，并调用它的方法
            Object myClassInstance = myClass.getDeclaredConstructor().newInstance();
            // ... 反射调用myClassInstance的方法等

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}